package com.lt.schoolchat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.schoolchat.annotation.AuthCheck;
import com.lt.schoolchat.common.BaseResponse;
import com.lt.schoolchat.common.DeleteRequest;
import com.lt.schoolchat.common.ErrorCode;
import com.lt.schoolchat.common.ResultUtils;
import com.lt.schoolchat.exception.BusinessException;
import com.lt.schoolchat.model.dto.history.SearchHistoryQueryRequest;
import com.lt.schoolchat.model.entity.SearchHistory;
import com.lt.schoolchat.service.SearchHistoryService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 查看搜索记录接口
 *
 * @author teng
 */
@RestController
@RequestMapping("/search_history")
@Api(tags = "查看搜索记录接口")
public class SearchHistoryController {
    @Resource
    private SearchHistoryService searchHistoryService;

    /**
     * 创建
     */
    @PostMapping("/add")
    public BaseResponse<Boolean> addSearchHistory(@RequestBody SearchHistory tagSearchHistory) {
        if (tagSearchHistory == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String word = tagSearchHistory.getWord();
        return ResultUtils.success(searchHistoryService.addSearchHistory(word));
    }

    /**
     * 删除
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSearchHistory(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        boolean b = searchHistoryService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 分页获取列表
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list/page")
    public BaseResponse<Page<SearchHistory>> listSearchHistoryByPage(
            SearchHistoryQueryRequest searchHistoryQueryRequest) {
        long current = 1;
        long size = 10;
        QueryWrapper<SearchHistory> queryWrapper = new QueryWrapper<>();
        if (searchHistoryQueryRequest != null) {
            // 根据标签名称模糊查询
            String word = searchHistoryQueryRequest.getWord();
            if (StringUtils.isNotBlank(word)) {
                queryWrapper.like("word", word);
            }
        }
        Page<SearchHistory> searchHistoryPage = searchHistoryService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(searchHistoryPage);
    }
}
